import os
import json
from tkinter import *
from tkinter import filedialog, ttk, messagebox, simpledialog
from configobj import ConfigObj
import TabletoLua
import link_to_desc

class FileListWindow(Toplevel):
    def __init__(self, parent, table_notes, form_directory, maplink_directory=None):
        super().__init__(parent.root)
        self.title("表格文件列表")
        self.geometry("500x400")
        
        self.table_notes = table_notes
        self.form_directory = form_directory
        self.maplink_directory = maplink_directory
        self.parent = parent  # 保存父窗口引用
        self.status = 1  # 1 表示策划表格，2 表示996表格
        
        self.setup_ui()
    
    def setup_ui(self):
        # 创建一个 Frame 来包含 Treeview 和 Scrollbar
        frame = Frame(self)
        frame.pack(pady=10, padx=10, fill=BOTH, expand=True)

        # 创建 Treeview
        self.tree = ttk.Treeview(frame, columns=("filename", "note"), show="headings")
        self.tree.heading("filename", text="文件名")
        self.tree.heading("note", text="备注")
        self.tree.column("filename", width=200, anchor="w")
        self.tree.column("note", width=200, anchor="w")
        self.tree.pack(side=LEFT, fill=BOTH, expand=True)

        # 创建垂直滚动条
        scrollbar = Scrollbar(frame, orient="vertical", command=self.tree.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.tree.config(yscrollcommand=scrollbar.set)

        # 第一行增加两个按钮
        button_frame = Frame(self)
        button_frame.pack(pady=5, padx=10, fill=X)

        Button(button_frame, text="策划表格", command=self.show_planning_tables).pack(side=LEFT, padx=5)
        Button(button_frame, text="996表格", command=self.show_996_tables).pack(side=LEFT, padx=5)

        self.load_table_files(self.form_directory)
        
        self.tree.bind("<Double-Button-1>", self.open_file)
        self.tree.bind("<Button-3>", self.show_context_menu)
        
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="添加/编辑备注", command=self.add_or_edit_note)
    
    def load_table_files(self, directory):
        if directory and os.path.exists(directory):
            for i in self.tree.get_children():
                self.tree.delete(i)
            for file in os.listdir(directory):
                if file.endswith(".xls") or file.endswith(".xlsx") or file.endswith(".csv"):
                    prefix = "planning_" if self.status == 1 else "996_"
                    note = self.table_notes.get(prefix + file, "")
                    self.tree.insert("", "end", values=(file, note))
    
    def open_file(self, event):
        item = self.tree.selection()[0]
        filename = self.tree.item(item, "values")[0]
        folder = self.status == 1 and self.form_directory or os.path.dirname(self.maplink_directory)
        file_path = os.path.join(folder, filename)
        if os.path.exists(file_path):
            os.startfile(file_path)
        else:
            messagebox.showerror("错误", f"文件 {file_path} 不存在！")
    
    def show_context_menu(self, event):
        item = self.tree.identify_row(event.y)
        if item:
            self.tree.selection_set(item)
            self.context_menu.post(event.x_root, event.y_root)
    
    def add_or_edit_note(self):
        item = self.tree.selection()[0]
        filename = self.tree.item(item, "values")[0]
        current_note = self.tree.item(item, "values")[1]

        # 使用 Toplevel 对话框来处理备注的添加和编辑
        note_dialog = Toplevel(self)
        note_dialog.title("添加/编辑备注")
        note_dialog.geometry("300x100")

        label = Label(note_dialog, text=f"为 {filename} 添加/编辑备注：")
        label.pack(pady=10)

        entry = Entry(note_dialog, width=40)
        entry.insert(0, current_note)
        entry.pack(pady=5)

        def save_note():
            note = entry.get()
            if note is not None:  # 用户没有取消对话框
                self.tree.item(item, values=(filename, note))
                prefix = "planning_" if self.status == 1 else "996_"
                self.parent.save_note(prefix + filename, note)  # 调用父窗口的方法保存备注
                messagebox.showinfo("成功", "备注已保存！")
            note_dialog.destroy()

        button = Button(note_dialog, text="保存", command=save_note)
        button.pack(pady=5)

        # 使对话框保持在最前面
        note_dialog.grab_set()
        note_dialog.focus_set()
        note_dialog.wait_window()
    
    def show_planning_tables(self):
        self.status = 1
        self.load_table_files(self.form_directory)
    
    def show_996_tables(self):
        self.status = 2
        if self.maplink_directory and os.path.exists(self.maplink_directory):
            self.load_table_files(os.path.dirname(self.maplink_directory))
        else:
            messagebox.showerror("错误", "请先选择 maplink 文件地址！")


class Winbox:
    def __init__(self):
        self.conf_ini = "./Config.ini"
        self.config = ConfigObj(self.conf_ini, encoding="UTF8")
        if not os.path.exists(self.conf_ini):
            self.create_config()
        else:
            required_keys = ["FormDirectory", "ClientDirectory", "ServerDirectory", 
                             "mapLinkPath", "forwardColor", "returnColor"]
            for key in required_keys:
                if key not in self.config:
                    self.config[key] = ""
            self.config.write()
        self.root = Tk()
        self.root.title("一键生成 Lua")
        self.root.geometry("580x530")

        self.path = StringVar()
        self.path.set(os.path.abspath("."))
        self.table_notes = self.load_notes()

        self.setup_ui()

        self.root.mainloop()

    def load_notes(self):
        if os.path.exists("table_notes.json"):
            with open("table_notes.json", "r", encoding="utf-8") as f:
                return json.load(f)
        return {}

    def save_note(self, filename, note):
        self.table_notes[filename] = note
        with open("table_notes.json", "w", encoding="utf-8") as f:
            json.dump(self.table_notes, f, ensure_ascii=False, indent=4)

    def create_config(self):
        self.config["FormDirectory"] = ""
        self.config["ClientDirectory"] = ""
        self.config["ServerDirectory"] = ""
        self.config["mapLinkPath"] = ""
        self.config["forwardColor"] = "251"  # 默认前往颜色
        self.config["returnColor"] = "253"  # 默认返回颜色
        self.config.write()

    def save_config(self, item, value):
        self.config[item] = value
        self.config.write()

    def select_path(self, entry, config_key):
        current_path = entry.get()
        if entry == self.Entry_maplink_file:
            selected_path = filedialog.askopenfilename(
                initialdir=self.Entry_maplink_file.get(),
                filetypes=[("Excel files", "*.xls;*.xlsx"), ("All files", "*.*")],
            )
        else:
            selected_path = filedialog.askdirectory(initialdir=current_path)
        if selected_path:
            selected_path = selected_path.replace("/", "\\") + "\\"
            entry.delete(0, "end")
            entry.insert(0, selected_path)
            self.save_config(config_key, selected_path)

    def turn_lua(self):
        try:
            form_path = self.Entry_form_directory.get()
            client_path = self.Entry_client_directory.get()
            server_path = self.Entry_server_directory.get()

            files = TabletoLua.filesCount(form_path)
            self.Progressbar["maximum"] = len(files)
            self.Progressbar["value"] = 0
            self.text_tips.delete(1.0, "end")

            for file in files:
                TabletoLua.writeLuacsv(self, file, server_path, client_path, form_path)
                self.Progressbar["value"] += 1

            self.text_tips.insert("1.0", "Lua 文件生成完成！\n")
        except Exception as e:
            pass

    def export_maplink(self):
        try:
            maplink_path = self.Entry_maplink_file.get()
            forwardColor = self.Entry_forward_color.get()
            returnColor = self.Entry_return_color.get()
            
            maplink_path = maplink_path[0:-1]
            if os.path.isfile(maplink_path):
                link_to_desc.writeXlsx(self, maplink_path, maplink_path[0:-15], forwardColor, returnColor)
                self.text_tips.insert("1.0", "Maplink 导出完成！\n")
            else:
                messagebox.showerror("错误", "Maplink 文件路径无效！")
        except Exception as e:
            messagebox.showerror("错误", f"导出 Maplink 时发生错误: {e}")

    def setup_ui(self):
        Label(self.root, text="表格目录：").grid(row=1, column=0, sticky=E)
        self.Entry_form_directory = Entry(self.root, width=50)
        self.Entry_form_directory.insert(0, self.config["FormDirectory"])
        self.Entry_form_directory.grid(row=1, column=1)
        Button(self.root, text="打开", command=lambda: self.select_path(self.Entry_form_directory, "FormDirectory")).grid(row=1, column=2)

        Label(self.root, text="前端目录：").grid(row=2, column=0, sticky=E)
        self.Entry_client_directory = Entry(self.root, width=50)
        self.Entry_client_directory.insert(0, self.config["ClientDirectory"])
        self.Entry_client_directory.grid(row=2, column=1)
        Button(self.root, text="打开", command=lambda: self.select_path(self.Entry_client_directory, "ClientDirectory")).grid(row=2, column=2)

        Label(self.root, text="后端目录：").grid(row=3, column=0, sticky=E)
        self.Entry_server_directory = Entry(self.root, width=50)
        self.Entry_server_directory.insert(0, self.config["ServerDirectory"])
        self.Entry_server_directory.grid(row=3, column=1)
        Button(self.root, text="打开", command=lambda: self.select_path(self.Entry_server_directory, "ServerDirectory")).grid(row=3, column=2)

        Label(self.root, text="maplink文件地址：").grid(row=4, column=0, sticky=E)
        self.Entry_maplink_file = Entry(self.root, width=50)
        self.Entry_maplink_file.insert(0, self.config["mapLinkPath"])
        self.Entry_maplink_file.grid(row=4, column=1)
        Button(self.root, text="打开", command=lambda: self.select_path(self.Entry_maplink_file, "mapLinkPath")).grid(row=4, column=2)

        Label(self.root, text="前往颜色：").grid(row=5, column=0, sticky=E)
        self.Entry_forward_color = Entry(self.root, width=50)
        self.Entry_forward_color.insert(0, self.config["forwardColor"])
        self.Entry_forward_color.grid(row=5, column=1)

        Label(self.root, text="返回颜色：").grid(row=6, column=0, sticky=E)
        self.Entry_return_color = Entry(self.root, width=50)
        self.Entry_return_color.insert(0, self.config["returnColor"])
        self.Entry_return_color.grid(row=6, column=1)

        self.text_tips = Text(self.root, width=50, height=18, fg="red")
        self.text_tips.insert("1.0", "准备就绪...\n")
        self.text_tips.grid(row=7, column=0, columnspan=3, pady=10)

        self.Progressbar = ttk.Progressbar(self.root, length=355)
        self.Progressbar.grid(row=8, column=0, columnspan=3, pady=10)

        Button(self.root, text="查看", command=self.show_file_list).grid(row=9, column=1, sticky=W)
        Button(self.root, text="地图标识", command=self.export_maplink).grid(row=9, column=1, sticky=E)
        Button(self.root, text="一键导出", command=self.turn_lua).grid(row=9, column=2, sticky=E)

    def show_file_list(self):
        form_directory = self.Entry_form_directory.get()
        maplink_directory = os.path.dirname(self.Entry_maplink_file.get())
        if form_directory and os.path.exists(form_directory):
            FileListWindow(self, self.table_notes, form_directory, maplink_directory)
        else:
            messagebox.showerror("错误", "请先选择表格目录！")

if __name__ == "__main__":
    Winbox()